using System;
using System.Collections;
using System.Management;
using NAnt.Core;
using NAnt.Core.Attributes;

[TaskName("sqlServerTcpAlias")]
public class EditSqlAlias : Task
{
	private string aliasName;
	private string serverName;
	private int portNum;
	private string clientMachineName = "localhost";

	public void cool(Project project)
	{
		string output = string.Empty;
		foreach (DictionaryEntry dictionaryEntry in project.Properties)
		{
			string name = dictionaryEntry.Key.ToString();
			if (name.ToLower().StartsWith("AppSettings."))
			{
				output+= "," + name.Substring(name.IndexOf('.') + 1);
			}
		}
		project.Properties["appSettings"] = output.Substring(1);
	}

	[TaskAttribute("aliasName", Required = true)]
	public string AliasName
	{
		get { return aliasName; }
		set { aliasName = value; }
	}

	[TaskAttribute("serverName", Required = true)]
	public string ServerName
	{
		get { return serverName; }
		set { serverName = value; }
	}

	[TaskAttribute("port", Required = true)]
	public int PortNum
	{
		get { return portNum; }
		set { portNum = value; }
	}

	[TaskAttribute("clientMachineName", Required = false)]
	public string ClientMachineName
	{
		get { return clientMachineName; }
		set { clientMachineName = value; }
	}


	protected override void ExecuteTask()
	{
		ManagementScope scope = new ManagementScope(@"\\" + ClientMachineName + @"\root\Microsoft\SqlServer\ComputerManagement");
		ManagementClass clientAlias = new ManagementClass(scope, new ManagementPath("SqlServerAlias"), null);
		clientAlias.Get();
		ManagementObject theAlias = null;
		foreach (ManagementObject alias in clientAlias.GetInstances())
		{
			 if (ThisIsTheAliasImLookingFor(alias))
			 {
				 Log(Level.Info, "Found existing alias :'{0}'.", AliasName);
			 	theAlias = alias;
				 break;
			 }
		}
		if (theAlias==null)
		{
			Log(Level.Info, "Creating alias: '{0}'.", AliasName);
			theAlias = clientAlias.CreateInstance();
			theAlias.SetPropertyValue("AliasName", aliasName);
		}
		theAlias.SetPropertyValue("ServerName", ServerName);
		theAlias.SetPropertyValue("ProtocolName", "tcp");
		theAlias.SetPropertyValue("ConnectionString", PortNum.ToString());
		Log(Level.Info, "Saving Alias '{0}'.", AliasName);
		theAlias.Put();
	}

	
	public override void Log(Level messageLevel, string message, params object[] args)
	{
		if (!iAmJustTesting)
			base.Log(messageLevel, message, args);
		else 
			Console.WriteLine(message, args);
	}

	private bool ThisIsTheAliasImLookingFor(ManagementObject alias)
	{
		return String.Equals((String)alias.GetPropertyValue("AliasName"), aliasName) &&
		       String.Equals((String)alias.GetPropertyValue("ProtocolName"), "tcp");
	}

	private bool iAmJustTesting = false;



}
